<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\UserDetail;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use Hash;
use Validator;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $validator=Validator::make($request->all(), [
            'name' => 'required',
            'password' => 'required',
        ]);
        //验证失败
        if($validator->fails()){
            return self::result(false,"请按要求填写信息",null);
        }
        $data=$request->all();
        //判断用户是否存在
        $user=User::where('name',$data['name'])->first();
        if(!isset($user->id))
        {
            return self::result(false,"不存在该用户",null);
        }
        try{
            if(Hash::check($data['password'],$user->password))
            {
                $token=str_random(40);
                $user->remember_token=$token;
                $user->save();
                $res['token']=$token;
                $res['id']=$user->id;
                return self::result(true,"登录成功",$res);
            }
            //密码不匹配
            return self::result(false,"账号或密码错误",null);
        }catch(DecryptException $e)
        {
            return self::result(false,"服务器爆炸",null);
        }
    }

    public function register(Request $request)
    {
        //验证数据
        $validator=Validator::make($request->all(),[
            "name"=>"required|max:20",
            "password"=>"required|max:60",
            //"email"=>"required|email|max:255",
        ]);

        if($validator->fails()){
            return self::result(false,"请按要求填写信息",null);
        }

        $data=$request->all();
        if(User::where('name',$data['name'])->first()!=null)
        {
            return self::result(false,"该用户已经存在",null);
        }
        $user=new User();
        //对密码进行加密
        $user->password=bcrypt($data['password']);
        $user->name=$data['name'];
        //$user->email=$data['email'];
        $user->save();
        //同时创建对应的用户详情
        $detail=UserDetail::create(['user_id'=>$user->id]);
        $detail->save();
        return self::result(true,"注册成功",null);
    }


    public static function result($success,$info,$res)
    {
        return ['success'=>$success,'info'=>$info,'result'=>$res];
    }


}
